import { Directive, inject, OnDestroy } from '@angular/core';
import { PageComponent } from '@shared/components/page.component';
import { MatDialogRef } from '@angular/material/dialog';
import { NavigationStart, Router, Event } from '@angular/router';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';

/**
 * 对话框组件基类
 * 
 * 功能特性：
 * - 继承 PageComponent 的加载状态管理
 * - 自动在路由导航时关闭对话框
 */
@Directive()
export abstract class DialogComponent<T, R = any> extends PageComponent implements OnDestroy {

  // 使用 inject 函数注入 Router
  protected router = inject(Router);
  
  // 路由订阅引用
  private routerSubscription: Subscription;

  // MatDialogRef 必须通过构造函数注入（由 Angular Material Dialog 框架提供）
  protected constructor(protected dialogRef: MatDialogRef<T, R>) {
    super();
    
    // 监听路由导航事件，自动关闭对话框
    this.routerSubscription = this.router.events
      .pipe(
        filter((event: Event) => event instanceof NavigationStart),
        filter(() => !!this.dialogRef)
      )
      .subscribe(() => {
        this.dialogRef.close();
      });
  }

  override ngOnDestroy(): void {
    super.ngOnDestroy();
    // 清理订阅
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
    }
  }
}
